package com.rephilo.zk.service;

import com.rephilo.zk.DataSourceUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class ZookeeperListener {

    private static final String PATH = "/jdbc-ref";

    @Autowired
    private CuratorFramework client;

    private NodeCache nodeCache;

    @PostConstruct
    public void initListener() throws Exception {
        //注册监听
        nodeCache = new NodeCache(client, PATH);
        nodeCache.getListenable().addListener(this::changeDataSource);
        nodeCache.start();
    }

    private void changeDataSource() throws Exception {
        byte[] bytes = client.getData().forPath(PATH);
        DataSourceUtils.setDataSource(new String(bytes));
    }

    public void setData(String url) throws Exception {
        Stat stat = client.checkExists().forPath(PATH);
        if (stat != null) {
            client.setData().forPath(PATH, url.getBytes());
        } else {
            client.create().forPath(PATH, url.getBytes());
        }
    }
}
